package com.frejoys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.dto.admin.StoreSaleListAndPageDto;
import com.frejoys.common.dto.store.StoreSaleListDto;
import com.frejoys.common.enums.EFileSize;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.util.AppConfigUtil;
import com.frejoys.common.util.TimeUtil;
import com.frejoys.common.vo.admin.StoreStatisticsListVo;
import com.frejoys.common.vo.store.StoreStatisticsDayVo;
import com.frejoys.dao.entity.Store;
import com.frejoys.dao.entity.StoreSale;
import com.frejoys.dao.entity.StoreStatisticsDay;
import com.frejoys.dao.mapper.StoreMapper;
import com.frejoys.dao.mapper.StoreStatisticsDayMapper;
import com.frejoys.service.StoreService;
import com.frejoys.service.StoreStatisticsDayService;
import com.frejoys.service.StoreUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wangzhicheng
 * @version 1.0
 * @date 2024/4/20 15:09
 */
@Service
@RequiredArgsConstructor
public class StoreStatisticsDayServiceImpl extends ServiceImpl<StoreStatisticsDayMapper, StoreStatisticsDay> implements StoreStatisticsDayService {

    private final StoreUserService storeUserService;

    private final StoreService storeService;

    private final StoreMapper storeMapper;

    @Override
    public List<StoreStatisticsDayVo> getList(StoreSaleListDto dto, Long userId) {


        List<Integer> storeIdByUserId = storeUserService.getStoreIdByUserId(userId);
        if (CollectionUtils.isEmpty(storeIdByUserId)) {
            return Collections.emptyList();
        }

        LambdaQueryWrapper<StoreStatisticsDay> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dto.getStoreId() != null, StoreStatisticsDay::getStoreId, dto.getStoreId());
        queryWrapper.in(StoreStatisticsDay::getStoreId, storeIdByUserId);
        if (dto.getYmd() != null && dto.getYmd() != 0) {
            queryWrapper.eq(StoreStatisticsDay::getYmd, dto.getYmd());
        } else if (dto.getYm() != null && dto.getYm() != 0) {
            queryWrapper.eq(StoreStatisticsDay::getYm, dto.getYm());
        } else if (dto.getY() != null && dto.getY() != 0) {
            queryWrapper.eq(StoreStatisticsDay::getY, dto.getY());
        }

        Page<StoreStatisticsDay> page = new Page<>(dto.getPage(), dto.getSize());
        page.setSearchCount(false);
        List<StoreStatisticsDay> records = baseMapper.selectPage(page, queryWrapper).getRecords();
        List<StoreStatisticsDayVo> vos = BeanUtil.copyToList(records, StoreStatisticsDayVo.class);
        List<Integer> storeIdList = vos.stream().map(StoreStatisticsDayVo::getStoreId).toList();
        if (CollectionUtils.isEmpty(storeIdList)) {
            return Collections.emptyList();
        }
        Map<Integer, String> idNameMap = storeService.getIdNameMap(storeIdList);
        for (StoreStatisticsDayVo vo : vos) {
            vo.setStoreName(idNameMap.get(vo.getStoreId()));
        }
        return vos;
    }


    @Override
    public IPage<StoreStatisticsListVo> storeStatisticsDayList(StoreSaleListAndPageDto dto) {

        Page<StoreStatisticsDay> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<StoreStatisticsDay> wrapper = new LambdaQueryWrapper<>();
        if (dto.getStoreId() != null){
            wrapper.eq(StoreStatisticsDay::getStoreId,dto.getStoreId());
        }
        if (StrUtil.isNotEmpty(dto.getStoreName())){
            List<Store> stores = storeMapper.getStoreNameById(dto.getStoreName());
            if (stores.isEmpty()){
                return new Page<>();
            }
            List<Integer> storeIds = stores.stream().map(Store::getId).toList();
            wrapper.in(StoreStatisticsDay::getStoreId,storeIds);
        }
        if (StrUtil.isNotEmpty(dto.getStartTime()) && StrUtil.isNotEmpty(dto.getEndTime())){

            //只能赛选三个月的订单
            Long day = TimeUtil.diffDay(TimeUtil.unixTime(dto.getStartTime()), TimeUtil.unixTime(dto.getEndTime()));
            if (day > 90){
                throw new GeneralException(HttpStatus.filtrationSaleError);
            }
            Integer startTime = Integer.valueOf(TimeUtil.formatYMD(TimeUtil.unixTime(dto.getStartTime())));
            Integer endTime = Integer.valueOf(TimeUtil.formatYMD(TimeUtil.unixTime(dto.getEndTime())));

            wrapper.ge(StoreStatisticsDay::getYmd,startTime);
            wrapper.le(StoreStatisticsDay::getYmd,endTime);
        }
        wrapper.orderByDesc(StoreStatisticsDay::getCreateTime);
        Page<StoreStatisticsDay> storeStatisticsDayPage = baseMapper.selectPage(page, wrapper);
        IPage<StoreStatisticsListVo> storeStatisticsListVoIPage = storeStatisticsDayPage.convert(storeStatisticsDay -> BeanUtil.copyProperties(storeStatisticsDay, StoreStatisticsListVo.class));
        List<StoreStatisticsListVo> list = storeStatisticsListVoIPage.getRecords();

        if (!list.isEmpty()){
            List<Integer> storeIds = list.stream().map(StoreStatisticsListVo::getStoreId).distinct().toList();

            //查询店铺信息
            List<Store> stores = storeMapper.getStoreNameList(storeIds);
            Map<Integer, Store> storeMap = stores.stream().collect(Collectors.toMap(Store::getId, store -> store));

            for (StoreStatisticsListVo vo:list) {

                if (storeMap.containsKey(vo.getStoreId())){
                    vo.setStoreName(storeMap.get(vo.getStoreId()).getName());
                    vo.setLogoUrl(AppConfigUtil.getUrlPrefix(storeMap.get(vo.getStoreId()).getLogo(), EFileSize.logo.getValue()));
                }
            }
        }
        return storeStatisticsListVoIPage;
    }

}
